// index.js
const app = getApp()
Page({
  data: {
    value: null,
    mapLocation: {
      longitude: 113.324520,  // 默认初始位置（广州）
      latitude: 23.099994
    },
    markers: [],                // 地图标记点
    scale: 14,                  // 地图缩放级别
    locationStatus: 'init',     // 定位状态：init/loading/success/failed
    useManualAddress: false,
    recList:[]
  },
  onShow(){
    wx.request({
      url: 'http://localhost:8080/system/recommend/list',
      method:"Get",
      header: {
        Authorization: app.globalData.token,
      },
      data:{},
      success:(res)=>{
        console.log(res);
        if(res.statusCode==200){
          this.setData({
            recList:res.data.rows
          })
          console.log(this.data.recList);
        }
      }
    })
  },
  toHotel(){
    wx.navigateTo({
      url: '/pages/hotel/hotel',
    })
  },
  stepAttractions(){
     wx.navigateTo({
       url: '/pages/attractions/attractions',
     })
  },
  goToResDetails(){
    // 固定餐馆名
    const resId = 1;
    // 跳转到 resDetailsghy 页面并传递 resId
    wx.navigateTo({
      url: `/pages/resDetailsghy/resDetailsghy?resId=${resId}`,
    });
  },
  onChange(e) {
    this.setData({
      value: e.detail,
    });
  },
  toStep(){
    wx.navigateTo({
      url: '/pages/hotel/hotel',
    })
  },
  onSearch() {
    Toast('搜索' + this.data.value);
  },
  onClick() {
    Toast('搜索' + this.data.value);
  },
  stepToRes(){
    wx.navigateTo({
      url: '/pages/resListwzh/resListwzh',
    })
  },
  stepToXq(e){
    console.log(e.currentTarget.dataset.id);
    wx.navigateTo({
      url: `/pages/recxqwzh/recxqwzh?id=${e.currentTarget.dataset.id}`,
    })
  },
  // 获取当前位置（包含权限处理）
  getLocation() {
    this.setData({ locationStatus: 'loading' });
    wx.showLoading({ title: '定位中...', mask: true });

    // 申请位置权限
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        // 权限通过，执行定位
        wx.getLocation({
          altitude: true,
          type: 'wgs84',  // 需与地图组件坐标系一致
          success: (res) => {
            wx.hideLoading();
            this.setData({
              mapLocation: {
                longitude: res.longitude,
                latitude: res.latitude
              },
              markers: [{
                id: 0,
                longitude: res.longitude,
                latitude: res.latitude,
                title: '当前位置',
                iconPath: 'navigation',  // 基础库内置图标（箭头样式）
                width: 40,
                height: 40
              }],
              locationStatus: 'success'
            });
            
            // 定位成功后，移动地图到当前位置
            this.moveToLocation();
          },
          fail: (err) => {
            wx.hideLoading();
            this.setData({ locationStatus: 'failed' });
            wx.showToast({ title: '定位失败，请重试', icon: 'none' });
            this.handleLocationError(err);
          }
        });
      },
      fail: (err) => {
        wx.hideLoading();
        this.setData({ locationStatus: 'failed' });
        this.handleLocationError(err);
      }
    });
  },

  // 处理定位错误
  handleLocationError(err) {
    if (err.errMsg.includes('auth deny')) {
      wx.showModal({
        title: '需要位置权限',
        content: '请在设置中授予位置权限',
        success: (res) => {
          if (res.confirm) wx.openSetting();
        }
      });
    } else {
      this.showManualInputOption();
    }
  },

  // 手动输入地址弹窗
  showManualInputOption() {
    wx.showModal({
      title: '位置获取失败',
      content: '是否切换到手动输入地址？',
      success: (res) => {
        if (res.confirm) this.setData({ useManualAddress: true });
      }
    });
  },

  // 移动地图到当前位置
  moveToLocation() {
    const { longitude, latitude } = this.data.mapLocation;
    wx.createMapContext('myMap').moveToLocation({
      longitude,
      latitude
    });
  },

  onLoad() {
    // 页面加载时可选择自动定位
     this.getLocation();
  }
})
